package ga;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;

import ui.Map;
import ui.MapView;

public class GARunner {
	
	public static final String POINTS_FILE = "C:/Users/juka/Desktop/points.txt";
	
	public static void main(String [] args) throws Exception{
		
		
		List<Point> points = readPointsFromFile(POINTS_FILE);
//		List<Point> points = generateRandomPoints(20);
		for (Point point : points) {
			PathManager.addPoint(point);
		}
		
		Population pop = new Population(100, true);
		System.out.println("Initial distance (without evolving): " + pop.getFittest().getDistance());
		
        for (int i = 0; i < 200; i++) {
            pop = GA.evolvePopulation(pop);
        }

        System.out.println("Final distance: " + pop.getFittest().getDistance());
        System.out.println("Solution:");
        System.out.println(pop.getFittest());
        
        MapView mv = new MapView();
        mv.setFittest(pop.getFittest());
	}



	private static List<Point> generateRandomPoints(int pointsTotal) {
		Random rnd = new Random();
		List<Point> points = new ArrayList<Point>();
		for(int i = 0; i<pointsTotal; i++){
			int x = rnd.nextInt(Map.WIDTH);
			int y = rnd.nextInt(Map.HEIGHT);
			points.add(new Point(x, y));
		}
		return points;
	}



	private static List<Point> readPointsFromFile(String pointsFile) throws IOException {
		BufferedReader in = new BufferedReader(new FileReader(pointsFile));
		String line = in.readLine().trim();
		int nPoints = Integer.parseInt(line);
		List<Point> points = new ArrayList<Point>();
		for (int i = 0; i < nPoints; i++) {
			line = in.readLine();
			StringTokenizer st = new StringTokenizer(line);
			int x = Integer.parseInt(st.nextToken());
			int y = Integer.parseInt(st.nextToken());
			
			Point p = new Point(x, y);
			points.add(p);
		}
		in.close();
		
		return points;
	}
	
}
